<template>
    <div style="margin: 15px; margin-right: 30px;">
        <el-form ref="form" :rules="rules" :model="form" label-width="130px">
            <!--  prop="chooseAddress" 解决第一个无法验证bug -->
            <el-form-item label="选择装货地址"  v-if="mapTag" prop="chooseAddress">
                <el-button
                type="text"
                icon="el-icon-position"
                @click="chooseAddress('load')"
                >地图选择</el-button>
            </el-form-item>
            <el-form-item label="装货地址" prop="shipperSubdivisionCodeList">
                <el-cascader
                    ref="loadAddress"
                    v-model="form.shipperSubdivisionCodeList"
                    :options="areaOptions"
                    :props="{ value: 'countyCode', label: 'countyName' }"
                    clearable
                    @change="changeConsignorAreaList"
                    :disabled="mapTag"
                />
            </el-form-item>
            <el-form-item label="装货详细地址" prop="consignorDetailAddress">
                <el-input v-model="form.consignorDetailAddress" placeholder="请输入装货详细地址" :disabled="mapTag" />
            </el-form-item>
            <el-form-item label="装货人姓名" prop="consignorName">
                <el-input v-model.trim="form.consignorName"  @change="(value)=>{form.consignorName = value.replace(/\s/g,'')}" placeholder="请输入装货人姓名" />
            </el-form-item>
            <el-form-item label="装货人电话" prop="consignorPhone">
                <el-input v-model="form.consignorPhone" placeholder="请输入装货人电话" />
            </el-form-item>
                <el-form-item label="选择收货地址" v-if="mapTag">
                  <el-button
                    type="text"
                    icon="el-icon-position"
                    @click="chooseAddress('consignee')"
                  >地图选择</el-button>
                </el-form-item>
            <el-form-item label="收货地址" prop="consigneeSubdivisionCodeList">
                <el-cascader
                    ref="unloadAddress"
                    v-model="form.consigneeSubdivisionCodeList"
                    :options="areaOptions"
                    :props="{ value: 'countyCode', label: 'countyName' }"
                    clearable
                    @change="changeConsigneeAreaList"
                    :disabled="mapTag"
                />
            </el-form-item>
            <el-form-item label="收货详细地址" prop="consigneeDetailAddress">
                <el-input v-model="form.consigneeDetailAddress" placeholder="请输入收货详细地址" :disabled="mapTag" />
            </el-form-item>
            <el-form-item label="收货人姓名" prop="consigneeName">
                <el-input v-model.trim="form.consigneeName" @change="(value)=>{form.consigneeName = value.replace(/\s/g,'')}" placeholder="请输入收货人姓名" />
            </el-form-item>
            <el-form-item label="收货人电话" prop="consigneePhone">
                <el-input v-model="form.consigneePhone" placeholder="请输入收货人电话" />
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="funcCancel">取 消</el-button>
            <el-button type="primary" @click="funcSubmit">确 定</el-button>
        </div>
        <vxe-modal v-model="mapDialog" width="65%" height="700" resize>
          <mapSelect v-if="modelFlag" ref="mapSelectDialog" @fatherMethod="fatherMethod"></mapSelect>
        </vxe-modal>
    </div>
</template>
<script>
import { getCommonRouteInfo, updateCommonRouteInfo } from '@/api/shipment'
import Cookies from "js-cookie"
import { GetMapTag } from "@/api/orderform"
import mapSelect from "@/views/components/mapSelect.vue"
import axios from "axios"
import {
    validatePhone,
    validateCellphone,
    validateTelephone,
} from '@/utils/validate.js'
export default {
    name: 'CommonRouteInfoEdit',
    components: {
      mapSelect
    },
    props: {
        areaOptions: {
            type: Array,
            default() {
                return []
            },
        },
        modelFlag:{
          type:Boolean,
          default(){
            return false
          }
        }
    },
    data() {
        return {
            form: {},
               rules: {
                shipperSubdivisionCodeList: [
                    {
                        required: true,
                        message: '请选择装货地址',
                        trigger: 'change',
                    },
                ],
                consignorDetailAddress: [
                    {
                        required: true,
                        message: '请输入装货详细地址',
                        trigger: 'blur',
                    },
                    {
                        min: 1,
                        max: 255,
                        message: '长度在 1 到 255 个字符',
                        trigger: 'blur',
                    },
                ],
                consignorName: [
                    {
                        required: true,
                        message: '请输入装货人姓名',
                        trigger: 'blur',
                    },
                    {
                        min: 1,
                        max: 255,
                        message: '长度在 1 到 255 个字符',
                        trigger: 'blur',
                    },
                ],
                consignorPhone: [
                    {
                        required: true,
                        validator(rule, value, callback) {
                            validatePhone(value)
                                ? callback()
                                : validateTelephone(value)
                                ? callback()
                                : callback(new Error('电话格式有误'))
                        },
                        trigger: 'blur',
                    },
                ],

                consigneeSubdivisionCodeList: [
                    {
                        required: true,
                        message: '请选择收货地址',
                        trigger: 'change',
                    },
                ],
                consigneeDetailAddress: [
                    {
                        required: true,
                        message: '请输入收货详细地址',
                        trigger: 'blur',
                    },
                    {
                        min: 1,
                        max: 255,
                        message: '长度在 1 到 255 个字符',
                        trigger: 'blur',
                    },
                ],
                consigneeName: [
                    {
                        required: true,
                        message: '请输入收货人姓名',
                        trigger: 'blur',
                    },
                    {
                        min: 1,
                        max: 255,
                        message: '长度在 1 到 255 个字符',
                        trigger: 'blur',
                    },
                ],
                // consigneePhone: [
                //   { required: true, message: "请输入收货人电话", trigger: "blur" },
                //   { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" }
                // ],
                consigneePhone: [
                    {
                        required: true,
                        validator(rule, value, callback) {
                            validatePhone(value)
                                ? callback()
                                : validateTelephone(value)
                                ? callback()
                                : callback(new Error('电话格式有误'))
                        },
                        trigger: 'blur',
                    },
                ],
            },
            mapType:'',
            mapDialog:false,
            mapTag:true
        }
    },
     created() {
        GetMapTag().then(res=>{
          this.mapTag = res.data=="1" ? true : false
        })
    },
    methods: {
        getInfo(code) {
            getCommonRouteInfo(code).then((response) => {
                this.form = response.data
            })
        },
        // 提交
        funcSubmit() {
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    const rLoading = this.openLoading()
                    updateCommonRouteInfo(this.form).then((response) => {
                        rLoading.close()
                        this.$message({
                            message: response.msg,
                            type: 'success',
                        })
                        this.$emit('fatherEditMethod')
                    })
                } else {
                    return false
                }
            })
        },
        // 取消
        funcCancel() {
            this.$emit('fatherCancelMethod', 'edit')
        },
        changeConsigneeAreaList() {
            this.form.consigneeProvinceCode = this.form.consigneeSubdivisionCodeList[0]
            this.form.consigneeCityCode = this.form.consigneeSubdivisionCodeList[1]
            this.form.consigneeCountyCode = this.form.consigneeSubdivisionCodeList[2]
        },
        changeConsignorAreaList() {
            this.form.consignorProvinceCode = this.form.shipperSubdivisionCodeList[0]
            this.form.consignorCityCode = this.form.shipperSubdivisionCodeList[1]
            this.form.consignorCountyCode = this.form.shipperSubdivisionCodeList[2]
        },
        // 地图选址
        chooseAddress(val) {
          this.mapDialog = true;
          this.mapType = val;
          // 调取查询地址的接口 显示位置再地图上
          let that = this;
          let addressQuery = ''
          let location = ''
          let adcode = ''
          let tab = ''
          if (val == "load") {
            addressQuery = this.form.consignorDetailAddress
            location =  this.form.shipperLongitude ? this.form.shipperLongitude +','+ this.form.shipperLatitude : ''
            adcode = this.form.consignorCountyCode
            if(location){
              let node = this.$refs["loadAddress"].getCheckedNodes()
              let nodes = node[0].pathNodes
              tab = {
                location:location,
                pname:nodes[0].label,
                cityname:nodes[1].label,
                adname:nodes[2].label,
                address:addressQuery,
                name:addressQuery,
                adcode:adcode
              }
            }
          } else if (val == "consignee") {
            addressQuery = this.form.consigneeDetailAddress
            location =  this.form.consigneeLongitude ? this.form.consigneeLongitude+','+this.form.consigneeLatitude : ''
            adcode = this.form.consigneeCountyCode
            if(location){
              let node = this.$refs["unloadAddress"].getCheckedNodes()
              let nodes = node[0].pathNodes
              tab = {
                location:location,
                pname:nodes[0].label,
                cityname:nodes[1].label,
                adname:nodes[2].label,
                address:addressQuery,
                name:addressQuery,
                adcode:adcode
              }
            }
          }
          // 坐标存在
          if (tab) {
            //console.log(tab)
            this.$refs.mapSelectDialog.initShow(tab)
          } else if (addressQuery !== "") {
          // 地址存在
          //console.log(addressQuery)
              axios
              .get("https://restapi.amap.com/v3/place/text", {
                params: { key: Cookies.get("GouldAMap"), keywords: addressQuery,city:adcode }
              })
              .then(function(response) {
                that.$refs.mapSelectDialog.initShow(response.data.pois[0]);
                // that.$refs.mapSelectDialog.query(that.form.shipmentPartyCode);
              }); 
          } else {
            this.$refs.mapSelectDialog.initShow()
          }
        },
        // 地图上选择的地址显示在文本框中
        fatherMethod(address, name, center,adcode) {
          let divisionValues = this.getDivisionValues(adcode)
          this.mapDialog = false;
          if (this.mapType == "load") {
            this.form.shipperSubdivisionCodeList = divisionValues
            this.form.consignorDetailAddress = name
            this.form.shipperLongitude = center[0]
            this.form.shipperLatitude = center[1]
            this.changeConsignorAreaList()
          } else if (this.mapType == "consignee") {
            this.form.consigneeSubdivisionCodeList = divisionValues
            this.form.consigneeDetailAddress = name
            this.form.consigneeLongitude = center[0]
            this.form.consigneeLatitude = center[1]
            this.changeConsigneeAreaList()
          }
        },
        getDivisionValues(adcode){
          let value=[]
          let getTag = false
          for (const key in this.areaOptions) {
            let item = this.areaOptions[key]
            for (const key1 in item.children) {
              let item1 = item.children[key1]
              for (const key2 in item1.children) {
                let item2 = item1.children[key2]
                if(item2.countyCode==adcode){
                  value.push(item.countyCode)
                  value.push(item1.countyCode)
                  value.push(adcode)
                  getTag = true
                  break
                }
              }
              if(getTag){
                break
              }
            }
            if(getTag){
                break
            }
          }
          return value
        }
    }
}
</script>
<style lang="scss" scoped>
.dialog-footer {
    margin: 15px 0 15px 0;
    width: 175px;
    float: right;
}
.el-cascader {
    width: 100%;
}
</style>
